package com.example.springbootjwt.config;

import com.example.springbootjwt.filter.JwtFilter;
import com.example.springbootjwt.filter.JwtLoginFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/7/11 18:22
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.inMemoryAuthentication().withUser("admin")
                .password("$2a$10$Tg3qH41r.M53Bse1axlUBefSpsEc88br3L.3NDTr2PmXwKsaAiJ12")
                .roles("admin")
                .and()
                .withUser("leo")
                .password("$2a$10$Tg3qH41r.M53Bse1axlUBefSpsEc88br3L.3NDTr2PmXwKsaAiJ12")
                .roles("user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests().antMatchers("/hello")
                .hasRole("user")
                .antMatchers("/admin")
                .hasRole("admin")
                .antMatchers(HttpMethod.POST,"/login")
                .permitAll()
                .anyRequest().authenticated()
                .and().addFilterBefore(new JwtLoginFilter("/login",authenticationManager()),
                UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JwtFilter(),UsernamePasswordAuthenticationFilter.class)
        .csrf().disable();
    }
}
